<template>
    <div>
        <Card v-if="totalProductNum===0">
            您尚未购买任何商品
        </Card>
        <div v-else>
            <Modal
                    v-model="confirmReceive"
                    title="Common Modal dialog box title"
                    @on-ok="confirmed"
                    @on-cancel="cancel">
                <p>确认收货</p>
            </Modal>
            <Row>
                <Col>
                    <Input v-model="searchName" placeholder="查询订单"></Input>
                </Col>
                <Col>
                    <Button @click="searchByName">点击查询</Button>
                </Col>
            </Row>
            <Card v-for="(item,index) in orderList" :value="item.orderId" :key="item.orderId">
                <Row>
                    <Col>
                        <Row style="height: 85px">
                            <img v-bind:src="CoverList[index]" style="height: 100%;width: auto">
                        </Row>
                        <Row type="flex" justify="center" align="middle">
                            <p>{{item.productName}}</p>
                        </Row>
                    </Col>
                    <Col>
                        <p>卖家信息</p>
                        <Row>
                            <Col>
                                <Avatar v-bind:src="sellerAvatarList[index]"></Avatar>
                            </Col>
                            {{item.sellerName}}
                        </Row>
                    </Col>
                    <Col>
                        <Row>
                            订单状态：{{ item.state }}
                        </Row>
                        <Row v-if="item.state===temp">
                            <Button @click="tempComment(index)">评价</Button>
                        </Row>
                        <Row v-else>
                            <Button @click="tempConfirm(index)">确认收货</Button>
                        </Row>
                    </Col>
                    <Col>
                        <Row>
                            <Button @click="talkToSeller(index)">联系卖家</Button>
                        </Row>
                        <Row>
                            <Button>退款</Button>
                        </Row>
                        <Row>
                            <Button @click="deleteOrder(item.orderId,index)">删除订单</Button>
                        </Row>
                    </Col>
                </Row>

            </Card>
            <Col class="mid">
                <Page :total="totalProductNum" @on-change="handlePage" show-total/>
            </Col>
            <Drawer
                    title="聊天窗格"
                    v-model="windowShow"
                    width="480"
                    :mask-closable="true"
            >
                <Layout>
                    <Content class="">
                        <Scroll height="480">
                            <Card v-for="item in MessageList" :key="item.messageItemId" :value="item.messageItemId">
                                <Row>
                                    <Col>
                                        <Avatar v-if="item.messageSenderId===userId" v-bind:src="userAvatar"></Avatar>
                                        <Avatar v-else v-bind:src="sellerAvatarList[index]"></Avatar>
                                    </Col>
                                    <Col>
                                        <p v-if="item.messageReceiverId===userId">{{item.senderName}}</p>
                                        <p v-else>{{userName}}</p>
                                    </Col>
                                    <Col>
                                        <p>{{item.messageSenderDate}}</p>
                                    </Col>
                                </Row>
                                <Row>
                                    <Col>
                                        {{ item.messageContent }}
                                    </Col>
                                </Row>
                            </Card>
                        </Scroll>
                    </Content>
                    <Footer>
                        <Form class="footer">
                            <Button class="send" @click="sentToSeller">发送</Button>
                            <Input v-model="questionContent" type="textarea" :rows="4" placeholder="请输入您想咨询的问题"></Input>
                        </Form>
                    </Footer>
                </Layout>
            </Drawer>
            <Drawer
                    title="Create"
                    v-model="commentDrawShow"
                    width="720"
            >
                <Card>
                    <p>多多评价可以涨经验哦~</p>
                </Card>
                <Form>
                    <Row>
                        <Rate allow-half v-model="comment.logisticsLevel" />
                    </Row>
                    <Row>
                        <Rate allow-half v-model="comment.productLevel" />
                    </Row>
                    <Row>
                        <Rate allow-half v-model="comment.serviceLevel" />
                    </Row>
                    <Row>
                        <Input type="textarea" placeholder="随便说点啥吧" v-model="comment.commentContent"></Input>
                    </Row>
                </Form>
                <div class="demo-drawer-footer">
                    <Button type="primary" @click="submitComment">提交!</Button>
                </div>
            </Drawer>
        </div>
    </div>
</template>

<script>
    import globalData from "@/utils/globalData";
    import axios from "axios";

    export default {
        name: "Order",
        data() {
            return {
                userId:'',
                userName:'',
                userAvatar:'',
                temp:"已确认收货",
                confirmReceive: false,
                confirmIndex: 0,
                searchName: "",
                nowPage: 1,
                windowShow: false,
                questionContent: '',
                totalProductNum: 0,
                orderList: [],
                CoverList: [],
                stateList: [],
                sellerAvatarList:[],
                comment:{
                    logisticsLevel:5.0,
                    productLevel:5.0,
                    serviceLevel:5.0,
                    commentContent:''
                },
                commentDrawShow:false,
                MessageList: [],
                readyToSentIndex: '',
                commentIndex:'',
                readyToSentSellerName: ''
            }
        },
        created: function () {
            this.userId=globalData.USER.userId
            this.userName=globalData.USER.nickName
            this.userAvatar=globalData.userAvatar
            let self = this
            axios({
                method: 'get',
                url: 'orderItem/buyerList/' + globalData.USER.userId + "/1"
            }).then(function (res) {
                console.log(res.data)
                self.orderList = res.data.content
                self.totalProductNum = res.data.totalElements
                //试图获取订单中商品的封面
                self.stateList = []
                for(let i =0;i<self.orderList.length;i++){
                    if (self.orderList[i].state === "已确认收货") {
                        self.$set(self.stateList,i,false)
                    }else {
                        self.$set(self.stateList,i,true)
                    }
                }
                for (let i = 0; i < self.orderList.length; i++) {
                    // self.stateList[i] = self.orderList
                    self.CoverList[i] = ''
                    self.sellerAvatarList[i]=''
                    axios({
                        method: 'get',
                        url: "/file/sig/product/" + self.orderList[i].coverUUID,
                        responseType: 'blob'
                    }).then(function (res) {
                        self.$set(self.CoverList, i, window.URL.createObjectURL(res.data))
                    })
                    //获取卖家头像
                    axios({
                        method:'get',
                        url:"/file/sig/avatar/"+self.orderList[i].sellerUUID,
                        responseType: 'blob'
                    }).then(function (res) {
                        self.$set(self.sellerAvatarList, i, window.URL.createObjectURL(res.data))
                    })
                }
            })
        },
        mounted() {
            let self = this
            if (this.windowShow) {
                this.timer = setInterval(() => {
                    self.getUnreadMessage()
                }, 1000)
            }
            //需要调用函数来让组件销毁的时候一并销毁掉setInterval，否则将会在切换到其他界面的时候仍然持续发起请求
            this.$once('hook:beforeDestroy', function () {
                clearTimeout(this.timer)
            })
        },
        methods: {
            confirmed() {
                this.$Message.success("确认收货成功")
                //前端更改界面的状态为已确认收货
                this.stateList[this.confirmIndex] = 3
                this.orderList[this.confirmIndex].state = "已确认收货"
                //后端更改状态
                axios({
                    method: 'patch',
                    url: '/orderItem/state/' + this.orderList[this.confirmIndex].orderId + "/已确认收货"
                })
            },
            cancel() {

            },
            submitComment(){
                let self = this
                let tempOrderItem = this.orderList[this.commentIndex]
                axios({
                    method:'patch',
                    url:"/product/comment",
                    data:{
                        orderId:tempOrderItem.orderId,
                        productId:tempOrderItem.productId,
                        buyerId:globalData.USER.userId,
                        sellerId:tempOrderItem.sellerId,
                        logisticsLevel:this.comment.logisticsLevel,
                        productLevel:this.comment.productLevel,
                        serviceLevel:this.comment.serviceLevel,
                        commentContent:this.comment.commentContent,
                    }
                }).then(function () {
                    self.$Message.success("评价成功！")
                })
            },
            tempComment(index){
                this.commentIndex=index
                this.commentDrawShow=true
            },
            tempConfirm(index) {
                this.confirmReceive = true
                this.confirmIndex = index
            },
            getUnreadMessage() {
                let self = this
                axios({
                    method: 'get',
                    url: 'message/unread/' + globalData.USER.userId + "/" + this.readyToSentSellerId
                }).then(function (res) {
                    let newMessageList = res.data
                    for (let i = 0; i < newMessageList.length; i++) {
                        self.MessageList.push(newMessageList[i])
                    }
                })
            },
            talkToSeller(index) {
                this.readyToSentSellerId = this.orderList[index].sellerId
                this.readyToSentSellerName = this.orderList[index].sellerName
                this.windowShow = true
                let self = this
                //在这里试图获取全部聊天
                //如果List为null的话就新建talker
                axios({
                    method: 'get',
                    url: 'message/list/' + globalData.USER.userId + "/" + this.readyToSentSellerId
                }).then(function (res) {
                    console.log(res.data)
                    console.log("hello" + res.data)
                    if (res.data == null) {
                        console.log("消息队列为空，新建会话")
                        axios({
                            method: 'post',
                            url: "/message/talker",
                            data: {
                                userId: globalData.USER.userId,
                                userName: globalData.USER.nickName,
                                userAvatarUUID: globalData.USER.avatarUUId,
                                otherId: self.readyToSentSellerId,
                                otherName: self.readyToSentSellerName,
                                otherAvatarUUID: self.orderList[index].sellerUUID
                            }
                        })
                    } else {
                        self.MessageList = res.data
                        console.log("has" + self.MessageList)
                    }
                })
            },
            sentToSeller() {
                axios({
                    method: 'post',
                    url: "/message/",
                    data: {
                        messageContent: this.questionContent,
                        messageSenderId: globalData.USER.userId,
                        senderName: globalData.USER.nickName,
                        messageReceiverId: this.readyToSentSellerId,
                        receiverName: this.readyToSentSellerName
                    }
                })
                this.MessageList.push({
                    messageItemId: new Date().getSeconds(),
                    messageSenderId: globalData.USER.userId,
                    messageContent: this.questionContent
                })
                //发送完之后清空发送框
                this.questionContent = ""
            },
            handlePage(value) {
                this.nowPage = value
                console.log(this.nowPage)
                this.search()
            },
            search() {
                axios({
                    method: 'get',
                    url: 'orderItem/buyerList/' + globalData.USER.userId + "/" + this.nowPage
                }).then(function (res) {
                    self.orderList = res.data.content
                })
            },
            searchByName() {
                let self = this
                axios({
                    method: 'get',
                    url: 'orderItem/PNCB/' + this.searchName + "/" + globalData.USER.userId + "/" + this.nowPage
                }).then(function (res) {
                    self.orderList = res.data.content
                    self.totalProductNum = res.data.totalElements
                })
            },
            deleteOrder(orderId, index) {
                this.orderList.splice(index, 1);
                let self = this
                axios({
                    method: 'delete',
                    url: "orderItem/" + orderId
                }).then(function () {
                    self.$Notice.success({
                        title: "删除成功"
                    })
                })
            }
        }
    }
</script>

<style scoped>
    .mid {
        position: relative;
        margin: 0 auto;
        text-align: center;
    }
    .demo-drawer-footer{
        width: 100%;
        position: absolute;
        bottom: 0;
        left: 0;
        border-top: 1px solid #e8e8e8;
        padding: 10px 16px;
        text-align: right;
        background: #fff;
    }
</style>